import {
  getOrderCustomField,
  getOrderExportField,
  getOrderSysExportFields,
  saveAndExportField,
  saveExportField,
} from '../../../api/order'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import moment from 'moment/moment'

// 工单所有导出字段
const exportFieldList = ref<{ value: string; showClose?: boolean; name: string; type: number }[]>(
  [],
)

// 工单自定义字段
const customFieldList = ref<{ id: string; code: any; name: string; showAdd?: boolean }[]>([])
const __customFieldList = ref<typeof customFieldList.value>([])

// 工单系统初始化导出字段
const sysExportFieldList = ref<{ id: string; code: string; name: string; showAdd?: boolean }[]>([])
const __sysExportFieldList = ref<typeof sysExportFieldList.value>([])

// 获取工单所有导出字段
const getOrderExportFieldList = async () => {
  const res = await getOrderExportField()
  if (res.data.code == 20000) {
    exportFieldList.value = res.data.data.rows.map((field) => {
      field.showClose = false
      return field
    })
  } else {
    return res.data
  }
}

// 获取工单自定义字段
const getOrderCustomFieldList = async () => {
  const res = await getOrderCustomField()
  if (res.data.code == 20000) {
    customFieldList.value = res.data.data.rows.map((field) => {
      field.showAdd = false
      return field
    })
    __customFieldList.value = [...res.data.data.rows]
  } else {
    return res.data
  }
}

// 获取工单系统初始导出字段
const getOrderSysExportFieldList = async () => {
  const res = await getOrderSysExportFields()
  if (res.data.code == 20000) {
    sysExportFieldList.value = res.data.data.rows.map((field) => {
      field.showAdd = false
      return field
    })
    __sysExportFieldList.value = [...res.data.data.rows]
  } else {
    return res.data
  }
}

// 系统字段添加到导出字段
const addSysFieldToExportFields = (column: {
  code: string
  id: string
  name: string
  showAdd?: boolean
}) => {
  exportFieldList.value.push({
    name: column.name,
    type: 1,
    value: column.code,
    showClose: false,
  })
  const index = sysExportFieldList.value.findIndex((item) => item.id === column.id)
  sysExportFieldList.value.splice(index, 1)
}

// 自定义字段添加到导出字段
const addCustomFieldToExportFields = (column: {
  code: any
  id: string
  name: string
  showAdd?: boolean
}) => {
  exportFieldList.value.push({
    name: column.name,
    type: 2,
    value: column.id,
    showClose: false,
  })
  const index = customFieldList.value.findIndex((item) => item.id === column.id)
  customFieldList.value.splice(index, 1)
}

// 从导出字段中移除
const removeFromExportFields = (column: { name: string; type: number; value: string }) => {
  const index = exportFieldList.value.findIndex((item) => item.name === column.name)
  exportFieldList.value.splice(index, 1)
  if (column.type === 1) {
    const __column = __sysExportFieldList.value.find((item) => item.name === column.name)
    sysExportFieldList.value.push({ ...__column, showAdd: false })
  } else if (column.type === 2) {
    const __column = __customFieldList.value.find((item) => item.name === column.name)
    customFieldList.value.push({ ...__column, showAdd: false })
  }
}

// 添加全部字段
const addAllToExportFields = (type: number) => {
  if (type === 1) {
    sysExportFieldList.value.forEach((column) => {
      exportFieldList.value.push({
        name: column.name,
        type,
        value: column.code,
        showClose: false,
      })
    })
    sysExportFieldList.value = []
  } else if (type === 2) {
    customFieldList.value.forEach((column) => {
      exportFieldList.value.push({
        name: column.name,
        type,
        value: column.id,
        showClose: false,
      })
    })
    customFieldList.value = []
  }
}

// 移除全部导出字段
const removeAllExportField = () => {
  exportFieldList.value.forEach((column) => {
    if (column.type === 1) {
      const __column = __sysExportFieldList.value.find((item) => item.code === column.value)
      delete __column.showAdd
      sysExportFieldList.value.push(__column)
    } else if (column.type === 2) {
      const __column = __customFieldList.value.find((item) => item.id === column.value)
      delete __column.showAdd
      customFieldList.value.push(__column)
    }
  })
  exportFieldList.value = []
}

/**
 * 保存导出的字段
 * @returns
 */
const saveExportFieldList = async () => {
  if (exportFieldList.value.length === 0) {
    ElMessage({
      showClose: true,
      message: '至少选择一个导出字段',
      type: 'error',
      offset: 200,
    })
    return
  }

  exportFieldList.value.forEach((column) => {
    delete column.showClose
  })

  const res = await saveExportField({ fieldAttrs: exportFieldList.value })
  ElMessage({
    showClose: true,
    message: res.data.message,
    type: res.data.success ? 'success' : 'error',
    offset: 200,
  })
}

// 保存并且导出字段
const saveAndExportFieldList = async (data) => {
  if (exportFieldList.value.length === 0) {
    ElMessage({
      showClose: true,
      message: '至少选择一个导出字段',
      type: 'error',
      offset: 200,
    })
    return false
  }

  exportFieldList.value.forEach((column) => {
    delete column.showClose
  })

  const res = await saveAndExportField({
    exportFieldVo: {
      fieldAttrs: exportFieldList.value,
    },
    selectVo: data,
  })
  /**
   * 因为前端把responseType: 'blob'放到请求头里，所以当后端响应JSON时也会把JSON转为blob
   * 所以需要将响应的数据转回JSON对象，如果转换成功就说明返回的是JSON，否则则是文件流
   */
  const reader = new FileReader()
  reader.readAsText(res.data)
  reader.onload = function (result) {
    try {
      // 解析对象成功，说明后端返回的是JSON
      const resData = JSON.parse(result.target.result as string)
      ElMessage({
        showClose: true,
        message: resData.message,
        type: 'warning',
        offset: 200,
      })
    } catch (err) {
      // 解析失败，说明后端返回的是文件流
      ElMessage({
        showClose: true,
        message: '部门数据导出成功',
        type: 'success',
        offset: 200,
      })
      const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
      const link = document.createElement('a')
      link.href = url
      link.download = `工单_${moment(new Date()).format('YYYYMMDD')}.xlsx`
      link.click()
    }
  }
}

export default {
  exportFieldList,
  customFieldList,
  sysExportFieldList,
  getOrderExportFieldList,
  getOrderCustomFieldList,
  getOrderSysExportFieldList,
  addAllToExportFields,
  addSysFieldToExportFields,
  addCustomFieldToExportFields,
  removeAllExportField,
  removeFromExportFields,
  saveExportFieldList,
  saveAndExportFieldList,
}
